//
//  JournalListController.m
//  DataStatistics
//
//  Created by Kang on 16/4/14.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "JournalListController.h"
#import "JournalViewModel.h"              //日志列表模型
#import "JournalListCell.h"
#import "EquipmenDetailsVC.h"            // 详情
//#import "CoustomerDetailsVC.h"      // 客户详情
#import "DTKDropdownMenuView.h"  //下拉框工具
#import "MapGPSViewController.h"     // GPS
#import "CommentsViewController.h"  // 交流圈
#import "CoverView.h"

#import "ControllerTool.h"
#define  reuseIdentifier  @"journalList"

@interface JournalListController ()<UITableViewDataSource,UITableViewDelegate>
{
    CoverView *cover;
    NSString *key;

}
/**
 *   判断刷新 ，true -刷新  float -加载
 */
@property (assign, nonatomic) BOOL isToUpdate;
/**
 *  数据页数
 */
@property (assign, nonatomic)  int page;
/**
 *  日志列表存放数据
 */
@property (strong, nonatomic) NSMutableArray *publicmodelAry;
/**
 *  获取点击的日志id
 */
@property (assign, nonatomic) int JLC_log_id;
@property (strong, nonatomic)UIButton *notDataBtn;

@end

@implementation JournalListController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initRightBarButtonItem];
    [self updateUI];
//    [self welcome];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(void)welcome
{
    cover = [[CoverView alloc]init];
    
    [cover setCoverObjectForKey:key = @"JournalListView"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapView)];
    
    [cover.DevicesView addGestureRecognizer:tap];
}


-(void)TapView
{
    [cover.DevicesView removeFromSuperview];
    
    [[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:key];
    
}




#pragma mark - TableView Data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.publicmodelAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cellHeight = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return CGRectGetHeight(cellHeight.frame);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JournalListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"journalList"];
    [cell vlueWithList:self.publicmodelAry[indexPath.row]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.JLC_log_id  = (int)[self.publicmodelAry[indexPath.row] log_id];
    [JournalViewModel journalDetailWithListModel:self.publicmodelAry[indexPath.row] forViewController:self];
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath {
    if ([ROLEDODE isEqualToString:@"006"]) {
        return UITableViewCellEditingStyleDelete;
    }
    else {
        return UITableViewCellEditingStyleNone;
    }
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        NSDictionary* dic = @{ @"log_id" : @((int)[self.publicmodelAry[indexPath.row] log_id]),@"delete":@"1"};

        [JournalViewModel requestWithUrlForChangePassword:@"dailylogInfo/falsedelete.asp?" andParam:dic success:^(JournalModel *model) {
        
            
            if ([model isEqual:@(1)]) {
                
                [self.publicmodelAry removeObjectAtIndex:indexPath.row]; //删除数据源
                
                [self.journalTableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationAutomatic]; //删除自己tavleView 的数据
                [self updateUI];
            }

        } failure:^(NSString *error) {
            
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
            
        }];
        
        
        
    }
}




#pragma mark - Other
// 更新数据，布局UI
- (void)updateUI {
    self.title =self.journalDeviceCode;
    self.isToUpdate = YES;
    self.page = 1;
    self.journalTableView.backgroundColor = [UIColor blackColor];
    
    if (self.journalDeviceCode == nil) {
        self.journalDeviceCode = [[NSUserDefaults standardUserDefaults] objectForKey:@"journalDevice"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"journalDevice"];
    }
    
    NSDictionary *dic = @{@"deviceCode":self.journalDeviceCode};
    [JournalViewModel requestWithUrlForRemoveUnreadNum:self andParam:dic failure:^(NSString *mag) {
        NSLog(@"mag:----->%@",mag);
    }];
    [self refreshTableView];
}

- (void)refreshTableView {
    self.journalTableView.separatorStyle = UITableViewCellEditingStyleNone;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isToUpdate = YES;
        self.page = 1;
        [self requestUrlViewWithPage:self.page];
    }];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    [header beginRefreshing];
    self.journalTableView.header = header;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.isToUpdate = NO;
        self.page++;
        [self requestUrlViewWithPage:self.page];
    }];
    self.journalTableView.footer = footer;
    
}
- (void)requestUrlViewWithPage:(int)page {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:self.journalDeviceCode forKey:@"deviceCode"];
    [dic setObject:[NSNumber numberWithInt:0] forKey:@"log_id"];
    [dic setObject:[NSNumber numberWithInt:page] forKey:@"current_page"];
    [JournalViewModel requestWithUrlForJournal:self andParam:dic success:^(JournalModel *model) {
        [self.journalTableView.footer endRefreshing];
        [self.journalTableView.header endRefreshing];
        //JouList *list  = model.JouList;
        if (_isToUpdate) {
            if ([model.JouList count] <= 0) {
                self.publicmodelAry = nil;
                //  if ([self.notDataBtn isEqual:[NSNull null]]) {
                [self.journalTableView addSubview:[self notDataBtn]];
                // }
                [self.journalTableView reloadData];
            }else {
                self.publicmodelAry = nil;
                self.publicmodelAry = model.JouList;
                [self.notDataBtn removeFromSuperview];
                [self.journalTableView reloadData];
            }
        }else {
            if ([model.JouList count] <= 0) {
                [self.journalTableView.footer endRefreshingWithNoMoreData];
            }else {
                NSMutableArray *mutaAry = [[NSMutableArray alloc] init];
                [mutaAry addObjectsFromArray:self.publicmodelAry];
                [mutaAry addObjectsFromArray:model.JouList];
                self.publicmodelAry = mutaAry;
                [self.journalTableView reloadData];
            }
        }
        
    } failure:^(NSString *error) {
        [self.journalTableView.footer endRefreshing];
        [self.journalTableView.header endRefreshing];
    }];
}
// 下拉框
- (void)initRightBarButtonItem {
    __weak typeof(self) weakSelf = self;
    
    DTKDropdownItem *item0 = [DTKDropdownItem itemWithTitle:NSLocalizedString(@"JLVCdetails", nil) iconName:@"Details-icon" callBack:^(NSUInteger index, id info) {
        NSLog(@"rightItem%lu",(unsigned long)index);
        [weakSelf DropdownPush:[NSString stringWithFormat:@"%lu",(unsigned long)index]];
    }];
    DTKDropdownItem *item1 = [DTKDropdownItem itemWithTitle:NSLocalizedString(@"JLVCinfo", nil) iconName:@"Cilent info-icon" callBack:^(NSUInteger index, id info) {
        NSLog(@"rightItem%lu",(unsigned long)index);
        [weakSelf DropdownPush:[NSString stringWithFormat:@"%lu",(unsigned long)index]];
    }];
    DTKDropdownItem *item2 = [DTKDropdownItem itemWithTitle:NSLocalizedString(@"JLVCgps", nil) iconName:@"GPS-icon" callBack:^(NSUInteger index, id info) {
        NSLog(@"rightItem%lu",(unsigned long)index);
        [weakSelf DropdownPush:[NSString stringWithFormat:@"%lu",(unsigned long)index]];
    }];
    DTKDropdownItem *item3 = [DTKDropdownItem itemWithTitle:NSLocalizedString(@"JLVCPicture", @"图片") iconName:@"Details-icon" callBack:^(NSUInteger index, id info) {
        NSLog(@"rightItem%lu",(unsigned long)index);
        [weakSelf DropdownPush:[NSString stringWithFormat:@"%lu",(unsigned long)index]];
    }];

    
    DTKDropdownMenuView *menuView = [DTKDropdownMenuView dropdownMenuViewWithType:dropDownTypeRightItem frame:CGRectMake(0, 0, 20, 30) dropdownItems:@[item0,item1,item2,item3] icon:@"更多菜单Icon"];
    menuView.dropWidth = 150.f;
    menuView.titleFont = [UIFont systemFontOfSize:18.f];
    menuView.textColor = [UIColor whiteColor];
    menuView.textFont = [UIFont systemFontOfSize:13.f];
    menuView.cellSeparatorColor = RGB(53.f, 54.f, 55.f, 1);
    menuView.textFont = [UIFont systemFontOfSize:14.f];
    menuView.cellColor = RGB(37, 38, 39, 1);
    menuView.animationDuration = 0.0f;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:menuView];
    
    UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] init];
    backIetm.title = NSLocalizedString(@"JLVCtitle", nil);
    self.navigationItem.backBarButtonItem = backIetm;
    
}


- (void)DropdownPush:(NSString *)integerStr {
    
    // 判断获取到的integer 是哪个，再来进行跳转。
    if ([integerStr isEqualToString:@"0"]) {
        EquipmenDetailsVC *eequVC = [[EquipmenDetailsVC alloc] init];
        eequVC.devicecode = self.journalDeviceCode;
        eequVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:eequVC animated:YES];
        
    }else if ([integerStr isEqualToString:@"1"]) {
        [self performSegueWithIdentifier:@"gotoCoustomerDetails" sender:self];
    }else if ([integerStr isEqualToString:@"2"]) {
        
        MapGPSViewController *map =[[MapGPSViewController alloc] init];
        map.mapDeviceCode = self.journalDeviceCode;
        [self.navigationController pushViewController:map animated:YES];
    }else if([integerStr isEqualToString:@"3"]){
        UIStoryboard * storyborad = [UIStoryboard storyboardWithName:@"Main" bundle:NULL];
        CommentsViewController * com =   [storyborad instantiateViewControllerWithIdentifier:@"comments"];
        com.commentsDeviceCode = self.journalDeviceCode;
        [self.navigationController pushViewController:com animated:YES];
    }
}


- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        _publicmodelAry = [[NSMutableArray alloc]init];
    }
    return self;
}

#pragma  mark - get / set
- (UIButton *)notDataBtn {
    if (!_notDataBtn) {
        _notDataBtn = [[UtilToolsClss getUtilTools] noDataBtn];
    }
    return _notDataBtn;
}

#pragma mark -Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier compare:@"gotoLogInfoC"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:self.journalDeviceCode forKey:@"logInfoDeviceCode"];
        [vc setValue:[NSNumber numberWithInt:self.JLC_log_id] forKey:@"logInfoID"];
    }else if ([segue.identifier compare:@"gotoCoustomerDetails"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:self.journalDeviceCode forKey:@"coustomerDeviceCode"];
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/




@end
